<!DOCTYPE html> 
<html>
  <head>
    <!--META-->
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">

    <!--CSS-->
    <link rel="shortcut icon" href="img/favicon.ico">
    <link rel="stylesheet" href="API/css/themes/default/jquery.mobile.min.css" />
    <link rel="stylesheet" href="API/css/mycss.css" />
    <link rel="stylesheet" href="css/mycss.css" />

    <!--JS-->
    <script type="text/javascript" src="include/config.js"></script>
    <script type="text/javascript" src="API/js/Jquery/jquery.min.js"></script>
    <script type="text/javascript" src="API/js/JqueryMobile/jquery.mobile.min.js"></script>
    <script type="text/javascript" src="API/js/functionsLib.js"></script>
    <script id="myWorker" type="javascript/webworker">
        var domaine = "http://localhost/ODA_OTR/";
        importScripts(domaine+'API/js/functionsNoJquery.js');
        
        /**
        * @name getLettreFroGridFromIndice
        * @param {int} p_indice
        * @param {int} p_modulo
        * @returns {String}
        */
        function getLettreFroGridFromIndice(p_indice, p_modulo) {
            try {
                var strRetour = "a";

                var reste = p_indice % p_modulo;

                switch (reste) { 
                    case 0: 
                        strRetour = "a";
                        break;  
                    case 1: 
                        strRetour = "b";
                        break;  
                    case 2: 
                        strRetour = "c";
                        break;  
                    case 3: 
                        strRetour = "d";
                        break;  
                    case 4: 
                        strRetour = "e";
                        break;  
                    case 5: 
                        strRetour = "f";
                        break;  
                    default: 
                        break; 
                }

                return strRetour;
            } catch (er) {
                log(0, "ERROR(getLettreFroGridFromIndice):" + er.message);
                return "";
            }
        }
        
        function getLettreFroGridFromIndice(p_indice, p_modulo) {
            try {
                var strRetour = "a";

                var reste = p_indice % p_modulo;

                switch (reste) { 
                    case 0: 
                        strRetour = "a";
                        break;  
                    case 1: 
                        strRetour = "b";
                        break;  
                    case 2: 
                        strRetour = "c";
                        break;  
                    case 3: 
                        strRetour = "d";
                        break;  
                    case 4: 
                        strRetour = "e";
                        break;  
                    case 5: 
                        strRetour = "f";
                        break;  
                    default: 
                        break; 
                }

                return strRetour;
            } catch (er) {
                log(0, "ERROR(getLettreFroGridFromIndice):" + er.message);
                return "";
            }
        }

        function messageHandler(event) {
            try {
                // On récupère le message envoyé par la page principale
                var messageSent = event.data;

                // On teste la commande envoyée
                switch (messageSent.cmd) {
                    case 'init':
                        // On peut initialiser certaines parties de nos objets qui serviront
                        // dans ce worker (attention au scope cependant !)
                        break;
                    case 'stop':
                        self.close(); // Terminates the worker.
                        break;
                    case 'lancer':
                        var p_code_user = messageSent.parameter.code_user;
                        var p_valeurPanierType = messageSent.parameter.valeurPanierType;
                        var p_mag = messageSent.parameter.mag;

                        var entree = new Date;
                        var entree = entree.getTime();

                        var percent = Math.round(0);
                        this.postMessage(new WorkerMessage('avancement', percent));

                        var tabListObj = new Array();
                        var subTabListObj = new Array();

                        var sql = "SELECT id, obj_label, obj_prix, obj_tr FROM `tab_ort` WHERE 1=1 AND `code_user` = '"+p_code_user+"';";

                        var tabInput = { sql : sql, keyAuthODA : '42c643cc44c593c5c2b4c5f6d40489dd' };
                        var return_json = µ.functionsOda.callRest(domaine+"API/phpsql/getSQL.php", {}, tabInput);

                        var returnSql = return_json["data"]["resultat"]["data"];

                        for (var indice in returnSql) {
                            subTabListObj = new Array();
                            subTabListObj[0] = "0";
                            subTabListObj[1] = returnSql[indice]["obj_label"];
                            subTabListObj[2] = returnSql[indice]["obj_prix"];
                            subTabListObj[3] = returnSql[indice]["obj_tr"];
                            tabListObj[returnSql[indice]["id"]] = subTabListObj;
                        }
                        
                        var tabInput = { "code_user" : p_code_user, "id_mag" : p_mag };
                        var return_json = µ.functionsOda.callRest(domaine+"phpsql/getStatPaniers.php", {}, tabInput);
                        var statsPanier = return_json.data.resultat;

                        var tabPaniers = new Array();

                        var strListeId = "";
                        var nbListeId = 0;
                        for (var indice in tabListObj) {
                            if(tabListObj[indice][0] == "0"){
                                strListeId += indice+",";
                                nbListeId += 1;
                            }
                        }
                        strListeId = strListeId.substring(0,strListeId.length-1);

                        var essai = 1;
                        var nbPanier = 0;

                        while(strListeId.length > 0){
                            var panierRest = statsPanier.nbPanierCible - nbPanier;
                            var old_strListeId = strListeId;

                            var tabInput = { "listeId" : strListeId, "panierMax" : p_valeurPanierType, "essai" : essai };
                            var return_json = µ.functionsOda.callRest(domaine+"phpsql/getCombi.php", {}, tabInput);
                            var returnSql = return_json["data"]["resultat"]["data"][0];

                            var tabContenuPanier = new Array();
                            var nbTrRest = 0;
                            for (var i = 1; i <= nbListeId; i++) {
                                var objId = returnSql["id_"+i];
                                var objPris = returnSql["obj"+i];
                                var objTr = returnSql["obj_tr"+i];
                                tabListObj[objId][0] = objPris;
                                if(objPris == "1"){
                                    tabContenuPanier[tabContenuPanier.length] = "id:"+objId;
                                }else if(objTr == "1"){
                                    nbTrRest++;
                                }
                            }
                            tabContenuPanier[tabContenuPanier.length] = "total:"+ returnSql["total"];
                            var rab = (nbTrRest-panierRest);
                            var oldTotal = 0;
                            
                            //opti essai
                            while((rab>=1)&&((returnSql["total"] != p_valeurPanierType)&&(oldTotal < parseFloat(returnSql["total"])))){
                                essai++;
                                var tabInput = { "listeId" : strListeId, "panierMax" : p_valeurPanierType, "essai" : essai };
                                var return_json = µ.functionsOda.callRest(domaine+"phpsql/getCombi.php", {}, tabInput);
                                var returnSql = return_json["data"]["resultat"]["data"][0];

                                var tabContenuPanier = new Array();
                                var nbTrRest = 0;
                                for (var i = 1; i <= nbListeId; i++) {
                                    var objId = returnSql["id_"+i];
                                    var objPris = returnSql["obj"+i];
                                    var objTr = returnSql["obj_tr"+i];
                                    tabListObj[objId][0] = objPris;
                                    if(objPris == "1"){
                                        tabContenuPanier[tabContenuPanier.length] = "id:"+objId;
                                    }else if(objTr == "1"){
                                        nbTrRest++;
                                    }
                                }
                                tabContenuPanier[tabContenuPanier.length] = "total:"+ returnSql["total"];
                                rab = (nbTrRest-panierRest);
                            }
                            
                            tabPaniers[tabPaniers.length] = tabContenuPanier;

                            var strListeId = "";
                            var nbListeId = 0;
                            for (var indice in tabListObj) {
                                if(tabListObj[indice][0] == "0"){
                                    strListeId += indice+",";
                                    nbListeId += 1;
                                }
                            }
                            strListeId = strListeId.substring(0,strListeId.length-1);
                            
                            nbPanier++;
                            var percent = Math.round(nbPanier/statsPanier.nbPanierCible*90);
                            this.postMessage(new WorkerMessage('avancement', percent));

                            if(old_strListeId == strListeId){
                                break;
                            }
                        }

                        var strhtml = "";
                        nbPanier = 0;

                        if(tabPaniers.length > 0){

                            var nblignes = (tabPaniers.length % 3) + 1;
                            var panierCourant = 0;

                            for (var i = 0; i < nblignes; i++) {

                                for (var j = 0; j < 3; j++) {

                                    if(tabPaniers[panierCourant] != undefined){

                                        var lettre = getLettreFroGridFromIndice(nbPanier, 4);
                                        nbPanier += 1;

                                        strhtml += "<div class=\"ui-block-"+lettre+"\">";
                                        strhtml += "<div class=\"ui-body ui-body-c\">";
                                        strhtml += "<center>";
                                        strhtml += "<table data-role=\"table\" data-mode=\"reflow\" class=\"ui-body-a ui-shadow table-stripe ui-responsive\">";
                                        strhtml += "<thead>";
                                        strhtml += "<TR class=\"ui-bar-b\">";
                                        strhtml += "<TH>Article</TH>";
                                        strhtml += "<TH>Prix</TH>";
                                        strhtml += "</thead>";
                                        strhtml += "<tbody>";
                                        for (var indice in tabPaniers[panierCourant]) {
                                            var id = tabPaniers[panierCourant][indice].split(":");
                                            strhtml += "<TR>";
                                            if(id[0] == "id"){
                                                strhtml += "<TD>"+tabListObj[id[1]][1]+((tabListObj[id[1]][3]=="1")?"*":"")+"</TD>";
                                                strhtml += "<TD>"+tabListObj[id[1]][2]+"&euro;</TD>";
                                            }else{
                                                strhtml += "<TD><b>Total</b> ("+(p_valeurPanierType - parseFloat(id[1])).toFixed(2)+"&euro;)</TD>";
                                                strhtml += "<TD><b>"+id[1]+"&euro;</b></TD>";
                                            }
                                            strhtml += "</TR>";
                                        }
                                        strhtml += "</tbody>";
                                        strhtml += "</table>";
                                    }
                                    panierCourant += 1;
                                    strhtml += "</center>";
                                    strhtml += "</div>";
                                    strhtml += "</div>";
                                }
                            }
                        }

                        var nb_article_restant = 0;
                        for (var indice in tabListObj) {
                            if(tabListObj[indice][0] == "0"){
                                nb_article_restant += 1;
                            }
                        }

                        if(nb_article_restant > 0){

                            var lettre = getLettreFroGridFromIndice(nbPanier, 4);
                            nbPanier += 1;

                            strhtml += "<div class=\"ui-block-"+lettre+"\">";
                            strhtml += "<div class=\"ui-body ui-body-c\">";
                            strhtml += "<center>";
                            strhtml += "Articles qui ne peuvent être mis dans des panniers payables par Ticket Restaurant : <br>";

                            strhtml += "<table data-role=\"table\" data-mode=\"reflow\" class=\"ui-body-a ui-shadow table-stripe ui-responsive\">";
                            strhtml += "<thead>";
                            strhtml += "<TR class=\"ui-bar-b\">";
                            strhtml += "<TH>Article</TH>";
                            strhtml += "<TH>Prix</TH>";
                            strhtml += "</thead>";
                            strhtml += "<tbody>";
                            for (var indice in tabListObj) {
                                if(tabListObj[indice][0] == "0"){
                                    strhtml += "<TR>";
                                    strhtml += "<TD>"+tabListObj[indice][1]+"</TD>";
                                    strhtml += "<TD>"+tabListObj[indice][2]+"&euro;</TD>";
                                    strhtml += "</TR>";
                                }
                            }
                            strhtml += "</tbody>";
                            strhtml += "</table>";
                            strhtml += "</center>";
                            strhtml += "</div>";
                            strhtml += "</div>";
                        }

                        var sql = "SELECT id, libelle, prix FROM `tab_ort_inventaire` WHERE 1=1 AND TR = 1 AND id_mag = "+p_mag+" ORDER BY prix asc LIMIT 0 , 5";
                        var tabInput = { sql : sql, keyAuthODA : '42c643cc44c593c5c2b4c5f6d40489dd' };
                        var return_json = µ.functionsOda.callRest(domaine+"API/phpsql/getSQL.php", {}, tabInput);
                        var returnSql = return_json["data"]["resultat"]["data"];

                        var lettre = getLettreFroGridFromIndice(nbPanier, 4);
                        nbPanier += 1;

                        strhtml += "<div class=\"ui-block-"+lettre+"\">";
                        strhtml += "<div class=\"ui-body ui-body-c\">";
                        strhtml += "<center>";
                        strhtml += "Sudgestion d'article pour vos paniers : <br>";
                        strhtml += "<table data-role=\"table\" data-mode=\"reflow\" class=\"ui-body-a ui-shadow table-stripe ui-responsive\">";
                        strhtml += "<thead>";
                        strhtml += "<TR bgcolor=\"#585858\" style=\"text-shadow:none;color:white;\">";
                        strhtml += "<TH>Article</TH>";
                        strhtml += "<TH>Prix</TH>";
                        strhtml += "<TH>Ajouter</TH>";
                        strhtml += "</thead>";
                        strhtml += "<tbody>";
                        for (var indice in returnSql) {
                            strhtml += "<TR>";
                            strhtml += "<TD>"+returnSql[indice]["libelle"]+"</TD>";
                            strhtml += "<TD>"+returnSql[indice]["prix"]+"&euro;</TD>";
                            strhtml += '<TD><a href="#" onclick="ajouterArticle('+returnSql[indice]["id"]+');" class="ui-btn ui-icon-plus ui-btn-icon-notext ui-corner-all" title="Ajouter article">Ajouter article</a></TD>';
                            strhtml += "</TR>";
                        }
                        strhtml += "</tbody>";
                        strhtml += "</table>";
                        strhtml += "</center>";
                        strhtml += "</div>";
                        strhtml += "</div>";

                        var fin = new Date;
                        var fin = fin.getTime();
                        var secondes = Math.round((fin-entree)/1000);
                        var hhmmss = µ.functionsOda.convertSecondsToTime(secondes);
                        this.postMessage(new WorkerMessage('stats',hhmmss));

                        this.postMessage(new WorkerMessage('resultats',strhtml));
                        break;
                    }
            }catch (er) {
                this.postMessage("Erreur : " + er.message);
                var tabInput = { type : 0, msg : "ERROR(WorkerPaniers):" + er.message };
                var retour = µ.functionsOda.callRest(domaine+"API/phpsql/insertLog.php", {}, tabInput);
            }
        }

        // On définit la fonction à appeler lorsque la page principale nous sollicite
        this.addEventListener('message', messageHandler, false);
    </script>

    <script type="text/javascript">
    ///////////////////
    //BLOCK VARIABLE GLOBAL
    ///////////////////
    var id_page = 1;
    var g_valeurPanierType = 0.00;
    var g_valeurTicket = 0.00;
    var g_mag = 0;
    var WorkerPaniers;

    ///////////////////
    //BLOCK FONCTIONS EVENEMENTS
    ///////////////////
    //Fin chargement page
    function OnLoad() {
        try {
            $( "#autocomplete_article" ).on( "filterablebeforefilter", function ( e, data ) {
                var $ul = $( this ),
                $input = $( data.input ),
                value = $input.val(),
                html = "";
                $ul.html( "" );
                if ( value && value.length > 3 ) {
                    $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
                    $ul.listview( "refresh" );
                    var tabInput = { recherche : $input.val(), id_mag : g_mag };
                    var retour = $.functionsLib.callRest(domaine+"phpsql/getArticleAutoCompl.php", {}, tabInput);
                    var json_retour = retour["data"]["resultat"]["data"];
                    for(var indice in json_retour){
                        html += "<li><a href=\"javascript:chargeArticle("+json_retour[indice]["id"]+",'"+json_retour[indice]["libelle"]+"',"+json_retour[indice]["prix"]+","+json_retour[indice]["tr"]+")\">"+json_retour[indice]["libelle"]+" - "+json_retour[indice]["prix"]+"€</a></li>";
                    }
                    $ul.html( html );
                    $ul.listview( "refresh" );
                    $ul.trigger( "updatelayout");
                }
            });
            
            charger_listeMag();
            afficheListe();
            afficherPanierType();
        } catch (er) {
            $.functionsLib.log(0, "ERROR(OnLoad):" + er.message);
        }
    }

    ///////////////////
    //BLOCK FONCTIONS METIER
    ///////////////////
    /**
     * @name chargeArticle
     * @param {string} p_id_article
     * @param {string} p_id_article
     * @param {string} p_id_article
     * @param {string} p_id_article
     */
    function chargeArticle(p_id_article, p_libelle, p_prix, p_tr){
        try {
            $( "#autocomplete_article" ).val('');
            $( "#autocomplete_article" ).html('');
            $( "#autocomplete_article" ).listview( "refresh" );
            $( "#autocomplete_article" ).trigger( "updatelayout");
            
            $( "#objLabel" ).val(p_libelle);
            $( "#objPrix" ).val(p_prix);
            $('input:radio[name="objTr"][value="0"]').prop('checked', false).checkboxradio("refresh");
            $('input:radio[name="objTr"][value="1"]').prop('checked', false).checkboxradio("refresh");
            $('input:radio[name="objTr"][value="'+p_tr+'"]').prop('checked', true).checkboxradio("refresh");
            
        } catch (er) {
            $.functionsLib.log(0, "ERROR(chargeArticle):" + er.message);
        }
    }
    
    /**
     * @name saisirObj
     * @description Saisir un nouvel article
     */
    function saisirObj(){
        try {
            var sql = "SELECT count(*) as nb FROM `tab_ort` WHERE 1=1 AND `code_user` = '"+$.functionsLib.getUserInfo().code_user+"';";

            var return_json = $.functionsLib.getSQL(sql);
            var retours = return_json["data"]["resultat"]["data"];
            
            var objNum = parseInt($('#objNum').val());

            var nbArticle = parseInt(retours[0]["nb"]);

            if((nbArticle+objNum) > 17){
                $.functionsLib.notification("Nombre d'article maximum atteind (17).", $.functionsLib.oda_msg_color.INFO);
            }else{
                var objLabel = $('#objLabel').val();
                var objPrix = $('#objPrix').val();
                var objTr = $('input:radio[name=objTr]:checked').val();

                for(i = 0; i < objNum; i++){
                    var sql = "INSERT INTO `tab_ort` (`id` ,`code_user` ,`date_saisie` ,`obj_code` ,`obj_label` ,`obj_prix`, `obj_tr`)VALUES (NULL , '"+$.functionsLib.getUserInfo().code_user+"', CURRENT_TIMESTAMP , '', '"+objLabel+"', '"+objPrix+"', '"+objTr+"');";
                    $.functionsLib.insertSQL(sql);
                }

                $('#objLabel').val('');
                $('#objPrix').val('');
                $('#objNum').val(1);
                $('input:radio[name=objTr]:checked').attr('checked', false).checkboxradio('refresh',true);
                
                var tabInput = { id_mag : g_mag, libelle : objLabel, prix : objPrix, tr : objTr };
                var retour = $.functionsLib.callRest(domaine+"phpsql/recordArticle.php", {}, tabInput);

                afficheListe();
            }
        } catch (er) {
            $.functionsLib.log(0, "ERROR(saisirObj):" + er.message);
        }
    }
    
    /**
     * @name afficheListe
     * @description Affiche la liste stocker en base
     */
    function afficheListe(){
        try {
            var sql = "SELECT id, obj_label, obj_prix, obj_tr FROM `tab_ort` WHERE 1=1 AND `code_user` = '"+$.functionsLib.getUserInfo().code_user+"';";

            var return_json = $.functionsLib.getSQL(sql);
            var retours = return_json["data"]["resultat"]["data"];

            var strhtml = "";
            var total = 0;

            strhtml += "<table id=\"tabLaListe\" data-role=\"table\" data-mode=\"reflow\" class=\"ui-body-a table-stripe ui-responsive\">";
            strhtml += "<thead>";
            strhtml += "<TR class=\"ui-bar-b\">";
            strhtml += "<TH>Id</TH>";
            strhtml += "<TH>Article</TH>";
            strhtml += "<TH>Prix</TH>";
            strhtml += "<TH>Act</TH>";
            strhtml += "</thead>";
            strhtml += "<tbody>";
            for (var indice in retours) {
                strhtml += "<TR>";
                strhtml += "<TD>"+(parseInt(indice)+1)+"</TD>";
                strhtml += "<TD>"+retours[indice]["obj_label"]+"</TD>";
                var strEtoile = "";
                if(retours[indice]["obj_tr"] == "1"){
                        strEtoile = "*";
                }else{
                        strEtoile = "";
                }
                strhtml += "<TD>"+retours[indice]["obj_prix"]+"&euro;"+strEtoile+"</TD>";
                total += parseFloat(retours[indice]["obj_prix"]);
                strhtml += '<TD><a id="bt_messages_lus" onclick="retirerArticle('+retours[indice]["id"]+');" href="#" class="ui-btn ui-icon-delete ui-corner-all ui-btn-inline ui-btn-icon-notext" title="Retirer article">Retirer article</a></TD>';
                strhtml += "</TR>";
            }
            strhtml += "<TR>";
            strhtml += "<TD>&nbsp;</TD>";
            strhtml += "<TD><b>Total</b></TD>";
            strhtml += "<TD><b>"+total.toFixed(2)+"&euro;</b></TD>";
            strhtml += "<TD>&nbsp;</TD>";
            strhtml += "</TR>";
            strhtml += "</tbody>";
            strhtml += "</table>";
            strhtml += "<a href=\"javascript:viderListe();\" data-role=\"button\" data-inline=\"true\" data-icon=\"arrow-r\" data-mini=\"true\">Vider la liste</a>";

            $('#laListe').html(strhtml).trigger('create');

            $('#content_liste').collapsible( "expand" );
            $('#content_paniers').hide();
        } catch (er) {
            $.functionsLib.log(0, "ERROR(afficheListe):" + er.message);
        }
    }

    /**
     * @name retirerArticle
     * @description Retire un article de la liste
     * @param {int} p_id_article
     */
    function retirerArticle(p_id_article){
        try {
            var strSQL = "DELETE FROM `tab_ort` WHERE 1=1 AND `code_user` = '"+$.functionsLib.getUserInfo().code_user+"' AND id="+p_id_article+";";
            $.functionsLib.deleteSQL(strSQL);

            afficheListe();
        } catch (er) {
            $.functionsLib.log(0, "ERROR(retirerArticle):" + er.message);
        }
    }
	
    /**
     * @name ajouterArticle
     * @description Ajouter un article à la liste
     * @param {int} p_id
     */
    function ajouterArticle(p_id){
        try {
            var sql = "SELECT id, libelle, prix FROM `tab_ort_inventaire` WHERE 1=1 AND `id` = '"+p_id+"';";

            var returnSql = new Array();
            returnSql = $.functionsLib.getSQL(sql);
            var article = returnSql.data.resultat.data[0];

            var sql = "INSERT INTO `tab_ort` (`id` ,`code_user` ,`date_saisie` ,`obj_code` ,`obj_label` ,`obj_prix`, `obj_tr`)VALUES (NULL , '"+$.functionsLib.getUserInfo().code_user+"', CURRENT_TIMESTAMP , '', '"+article.libelle+"', '"+article.prix+"', '1');";
            $.functionsLib.insertSQL(sql);

            afficheListe();
        } catch (er) {
            $.functionsLib.log(0, "ERROR(ajouterArticle):" + er.message);
        }
    }
	
    /**
     * @name saisirPanier
     * @description Saisir les carractéristiques du panier type
     */
    function saisirPanier(){
        try {
            var nbTicket = $('#nbTicket').val();
            var valeurTicket = $('#valeurTicket').val();
            var id_mag = $('#listeMag').val();

            var strSQL = "REPLACE `tab_ort_panier_cible` (`id`, `code_user`, `nbTicket`, `valeurTicket`, `id_mag`) VALUES (NULL , '"+$.functionsLib.getUserInfo().code_user+"', '"+nbTicket+"', '"+valeurTicket+"', '"+id_mag+"');";
            $.functionsLib.insertSQL(strSQL);

            afficherPanierType();

            $('#content_contexte').collapsible( "collapse" );
        } catch (er) {
            $.functionsLib.log(0, "ERROR({):" + er.message);
        }
    }
	
    /**
     * @name afficherPanierType
     * @description Calcule et affiche le panier type dans la barre de l'encard
     */
    function afficherPanierType(){
        try {
            var sql = "SELECT nbTicket, valeurTicket, nom, id_mag FROM `tab_ort_panier_cible` a, `tab_ort_mags` b WHERE 1=1 AND a.id_mag = b.id AND `code_user` = '"+$.functionsLib.getUserInfo().code_user+"';";

            var return_json = $.functionsLib.getSQL(sql);
            var retours = return_json["data"]["resultat"]["data"];

            if(return_json["data"]["resultat"]["nombre"] == "0"){
                var strSQL = "REPLACE `tab_ort_panier_cible` (`code_user` ,`nbTicket` ,`valeurTicket`, `id_mag`) VALUES ('"+$.functionsLib.getUserInfo().code_user+"', 2,  8, 0);";
                $.functionsLib.insertSQL(strSQL);

                g_valeurPanierType = 16.00;
                g_valeurTicket = 8;
                g_mag = 0;

                $("#labelPanierType").html("Le contexte (2*8&euro;)");
            }else{
                var nbTicket = parseInt(retours[0]["nbTicket"]);
                var valeurTicket = parseFloat(retours[0]["valeurTicket"]).toFixed(2);
                var nomMag = retours[0]["nom"];
                var id_mag = retours[0]["id_mag"];

                g_mag = id_mag;
                g_valeurTicket = valeurTicket;
                g_valeurPanierType = nbTicket * valeurTicket;

                var strResume = "";
                if(nomMag != ""){
                    strResume = "Le contexte ("+nbTicket+"*"+valeurTicket+"&euro;"+" chez "+nomMag+")";
                }else{
                    strResume = "Le contexte ("+nbTicket+"*"+valeurTicket+"&euro;)";
                }

                $("#labelPanierType").html(strResume);
            }
            $('#nbTicket').val((g_valeurPanierType/g_valeurTicket));
            $('#valeurTicket').val(g_valeurTicket);
            $('#listeMag').val(g_mag);
            $('#listeMag').selectmenu();
            $("#listeMag").selectmenu('refresh', true);
        } catch (er) {
            $.functionsLib.log(0, "ERROR(afficherPanierType):" + er.message);
        }
    }
	
    /**
     * @name viderListe
     * @description Vide la liste d'article
     */
    function viderListe(){
        try {
            var strSQL = "DELETE FROM `tab_ort` WHERE 1=1 AND `code_user` = '"+$.functionsLib.getUserInfo().code_user+"';";
            $.functionsLib.deleteSQL(strSQL);

            afficheListe();
        } catch (er) {
            $.functionsLib.log(0, "ERROR({):" + er.message);
        }
    }
	
    /**
     * @name charger_listeMag
     * @description Charge la liste des magasins
     */
    function charger_listeMag() {
        try {
            var sql = "SELECT id, nom FROM `tab_ort_mags` WHERE 1=1;";

            var return_json = $.functionsLib.getSQL(sql);
            var retours = return_json["data"]["resultat"]["data"];

            for (var indice in retours) {
                $("#listeMag").append(new Option(retours[indice]["nom"],retours[indice]["id"]));
            }

            $('#listeMag').selectmenu();
            $("#listeMag").selectmenu('refresh', true);
        } catch (er) {
            $.functionsLib.log(0, "ERROR(charger_listeMag):" + er.message);
        }
    }
    
    /**
     * @name traitementCalculePaniers
     * @description Traitement
     */
    function traitementCalculePaniers() {
        try {
            var strhtml = "";

            $('#content_paniers').show();
            $('#content_console').collapsible( "collapse" );
            $('#content_liste').collapsible( "collapse" );

            /* Vérifie si les Web Workers sont supportés */
            if (window.Worker) {
                strhtml += "<IMG SRC=\"API/img/loading.gif\" ALT=\"Chargement\" TITLE=\"Chargement\">";
                $('#Label_lespaniers').html(strhtml);

                WorkerPaniers = $.functionsLib.initWorker("myWorker", traitementCalculePaniers_retour);

                var json_param = {"code_user" : $.functionsLib.getUserInfo().code_user, "valeurPanierType" : g_valeurPanierType, "mag" : g_mag};

                WorkerPaniers.postMessage(new WorkerMessage('lancer', json_param)); 
            } else {
                $('#Label_lespaniers').html("Les Web Workers ne sont pas supportés par votre navigateur. Réessayez avec IE10 : <a href=\"http://ie.microsoft.com/testdrive\">téléchargez la dernière Platform Preview d'IE10 </a>");
            }

        } catch (er) {
            $.functionsLib.log(0, "ERROR(traitementCalculePaniers):" + er.message);
        }
    }

    /**
     * @name traitementCalculePaniers_retour
     * @description Reception des messages retour du traitement
     * @param {string} p_message
     */
    function traitementCalculePaniers_retour(p_message) {
        try {
            switch (p_message.cmd) {
                case 'avancement':
                    var percent = p_message.parameter;
                    $('#Label_lespaniers').html("<p>Avancement de la t&acirc;che...<span id=\"labelProgress\">"+percent+"%</span><br><progress id=\"avancementProd\" value=\""+percent+"\" max=\"100\"></progress><img src=\"API/img/loading.gif\" alt=\"loading\" style=\"vertical-align:middle;\" /><br><a href=\"javascript:terminateWorkerPaniers();\">Annuler</a></p>").trigger('create');
                    break;
                case 'resultats':
                    $.functionsLib.terminateWorker(WorkerPaniers);
                    $('#lespaniers').html(p_message.parameter).trigger('create');
                    break;
                case 'stats':
                    $('#Label_lespaniers').html("Dur&eacute;e du traitement en "+p_message.parameter+".");
                    break;
                default: 
                    $.functionsLib.notification(p_message,$.functionsLib.oda_msg_color.WARNING);
            }
        } catch (er) {
            $.functionsLib.log(0, "ERROR(traitementCalculePaniers_retour):" + er.message);
        }
    }         
                
    /**
    * @name terminateWorkerPaniers
    * @description Appeller quant le worker à fini sa tâche
    */
    function terminateWorkerPaniers() {
       try {
           WorkerPaniers.terminate();
           $('#Label_lespaniers').html("Traitement annul&eacute;e");
       } catch (er) {
           $.functionsLib.log(0, "ERROR(terminateWorkerPaniers):" + er.message);
       }
   }
  </script>
	
  </head>
  <body onload="OnLoad();">
    <!-- page -->
    <div data-role="page">
	
        <!-- /panel -->
        <div data-role="panel" id="mypanel" data-display="overlay" data-position="left">

        </div>
        <!-- /panel -->

        <!-- header -->
        <div data-role="header" data-position="fixed">
            <a href="#mypanel" data-role="button" data-icon="home" data-iconpos="notext">home</a>
            <h1 id="id_titre">titre</h1>
            <a href="javascript:window.location = ('./api_page_contact.html?mili='+$.functionsLib.getMilise());" data-role="button" data-icon="info" data-iconpos="notext">Contact</a>
        </div>
        <!-- /header -->

        <!-- content -->
        <div data-role="content" id="main_content">
            <div data-role="collapsible" data-collapsed="false" id="content_console">
                <h3>Ajouter &eacute;l&eacute;ments au panier</h3>

                <div class="ui-grid-a ui-responsive">

                    <div class="ui-block-a">
                        <div data-role="fieldcontain">
                            <label for="objLabel" style="width: 100%">Saisir nom de l'article :</label><br>
                            <input type="text" name="objLabel" id="objLabel" value="" placeholder="ici"/>
                        </div>
                        <div data-role="fieldcontain">
                            <label for="objPrix" style="width: 100%">Saisir le prix :</label><br>
                            <input type="number" pattern="^\d+(\.\d{1,2})?$" name="objPrix" id="objPrix" value="" placeholder="00.00"/>
                        </div>
                    </div>
                    <div class="ui-block-b">	
                        <div data-role="fieldcontain">
                            <label for="objNum" style="width: 100%">Nombre :</label><br>
                            <input type="number" pattern="^\d+(\.\d{1,2})?$" name="objNum" id="objNum" value="1" placeholder="1"/>
                        </div>
                        
                        <fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">
                            <legend>Compatible Ticket Restaurant :</legend>
                            <input type="radio" name="objTr" id="objTr_1" value="1" />
                            <label for="objTr_1">Oui</label>
                            <input type="radio" name="objTr" id="objTr_0" value="0" />
                            <label for="objTr_0">Non</label>
                        </fieldset>
                    </div>

                </div>
                <label>Importer un article :</label>
                <ul id="autocomplete_article" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="4 lettres au moins..."></ul>
                
                <label>Actions :</label>
                <a href="javascript:saisirObj();" data-role="button" data-inline="true" data-icon="arrow-r" data-mini="true">Ajouter article</a>
                <a href="javascript:traitementCalculePaniers();" data-role="button" data-inline="true" data-icon="arrow-r" data-mini="true">Calculer les paniers</a>
            </div>

            <div data-role="collapsible" data-collapsed="true" id="content_liste">
                <h3>Votre liste</h3>
                <center><div id="laListe">la liste est vide.</div></center>
            </div>

            <div data-role="collapsible" data-collapsed="false" id="content_paniers">
                <h3>Vos paniers</h3>
                <div class="ui-grid-c ui-responsive" id="lespaniers"></div>
                <label id="Label_lespaniers"></label>
            </div>
            
            <div data-role="collapsible" data-collapsed="true" id="content_contexte">
                <h3><span id="labelPanierType">Panier par d&eacute;faut</span></h3>

                <div class="ui-grid-a ui-responsive">

                    <div class="ui-block-a">
                        <div data-role="fieldcontain">
                            <label for="nbTicket" style="width: 100%">Nombre de  ticket :</label><br>
                            <input type="number" pattern="^\d+$" name="nbTicket" id="nbTicket" value="" placeholder="0"/>
                        </div>
                        <div data-role="fieldcontain">
                            <label for="valeurTicket" style="width: 100%">Valeur du ticket :</label><br>
                            <input type="number" pattern="^\d+(\.\d{1,2})?$" name="valeurTicket" id="valeurTicket" placeholder="0.00"/>
                        </div>
                    </div>

                    <div class="ui-block-b">
                        <label for="listeMag" style="width: 100%">Choix du magasin : </label>
                        <SELECT name="listeMag" id="listeMag" data-native-menu="false">
                            <option value="" data-placeholder="true">Choix du magasin</option>
                        </SELECT>
                        <a href="javascript:saisirPanier();" data-role="button" data-inline="true" data-icon="arrow-r">Mettre à jour le pannier cible</a>
                    </div>

                </div>
            </div>
        
        </div>
        <!-- /content -->

        <!-- footer -->
        <div data-role="footer" data-position="fixed">
            <a data-role="button" data-icon="search" data-iconpos="notext" class="ui-btn-left" href="javascript:window.location = ('./api_page_faq.html?mili='+$.functionsLib.getMilise());">FAQ</a>
            <h1 id="id_affichageUser">User</h1>
            <a data-role="button" data-icon="delete" data-iconpos="notext" class="ui-btn-right" data-theme="c" href="javascript:window.location = ('./api_page_sortie.html?mili='+$.functionsLib.getMilise());">Logout</a>
        </div>
        <!-- /footer -->
		
    </div>
    <!-- /page -->
</body>
</html>